/**
 * 
 */
package kr.pe.johnkim.dayve.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import kr.pe.johnkim.dayve.provider.DayveGroup;
import kr.pe.johnkim.dayve.provider.DayveItem;
import kr.pe.johnkim.dayve.util.ExternalJoinConstant;

/**
 * Group RESTful 관련 기능들을 구현하는 클래스이다.
 * 
 * @author johnkim
 *
 */
public class DayveGroupRest {

	public static final String TAG = DayveGroupRest.class.getSimpleName();

	// 서버 주소.
	public static final String SERVER_URL = ExternalJoinConstant.MOBILE_SERVER_URL;

	// 컨트롤러 매핑.
	public static final String MYHISTORY_GROUP_CONTROLLER = "/myHistoryGroupController";
	
	// Group Name 중복 검사.
	public static final String MYHISTORY_GROUP_CHECK_DUPLICATION = "/checkDuplication";
	
	// Group 등록.
	public static final String MYHISTORY_GROUP_REGISTER = "/registerGroup";
	
	// Group 목록을 가져 온다.
	public static final String MYHISTORY_GROUP_LIST = "/selectGroupList";
	
	// Group 을 수정 한다.
	public static final String MYHISTORY_GROUP_UPDATE = "/updateGroup";
	
	// Group 을 비활성화 한다.
	public static final String MYHISTORY_GROUP_DEACTIVATE = "/updateDeactivateGroup";
	
	/**
	 * Group Name 중복 검사를 한다.
	 * 
	 * 등록되어 있는 Group Name 의 갯수를 가져 온다.
	 * 
	 * 1. Group Name 이 등록되어 있지 않으면 : 0
	 * 2. Group Name 이 이미 등록되어 있으면 : 1
	 * 3. 실행 중 오류 발생     : ERROR
	 * 
	 * @param dayveGroup
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveGroup checkDuplication(DayveGroup dayveGroup) throws JSONException, IOException {
		Log.i(TAG, "checkDuplication");
		
		JSONObject jsonGroup = new JSONObject();
		
		jsonGroup.put("name", dayveGroup.getName());
		jsonGroup.put("activateYn", dayveGroup.getActivateYn());
		jsonGroup.put("myHistoryMembersId", dayveGroup.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryGroup\":" + jsonGroup.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveGroup mDayveGroup = new DayveGroup();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_GROUP_CONTROLLER + MYHISTORY_GROUP_CHECK_DUPLICATION);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);

	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonGroup = new JSONObject(line);
	            	JSONObject mJsonGroup2 = mJsonGroup.getJSONObject("myHistoryGroup");
	            	
	            	mDayveGroup.setCount(mJsonGroup2.getString("count"));
	        	}
	        }
	        
	        Log.i(TAG, "Success to check duplication of group name.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.i(TAG, "Fail to check duplication of group name.");
			
			mDayveGroup.setCount("ERROR");
		}
		
		return mDayveGroup;
	}
	
	/**
	 * Group 을 등록 한다.
	 * 
	 * 등록 결과가 SUCCESS 나 FAIL 의 string 으로 반환 된다.
	 * 
	 * @param dayveGroup
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveGroup registerGroup(DayveGroup dayveGroup) throws JSONException, IOException {
		Log.i(TAG, "registerGroup");
		
		JSONObject jsonGroup = new JSONObject();
		
		jsonGroup.put("name", dayveGroup.getName());
		jsonGroup.put("comment", dayveGroup.getComment());
		jsonGroup.put("iconUrl", dayveGroup.getIconUrl());
		jsonGroup.put("openGroupYn", dayveGroup.getOpenGroupYn());
		jsonGroup.put("favoriteYn", dayveGroup.getFavoriteYn());
		jsonGroup.put("activateYn", dayveGroup.getActivateYn());
		jsonGroup.put("modifyDate", dayveGroup.getModifyDate());
		jsonGroup.put("registerDate", dayveGroup.getRegisterDate());
		jsonGroup.put("myHistoryMembersId", dayveGroup.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryGroup\":" + jsonGroup.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveGroup mDayveGroup = new DayveGroup();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_GROUP_CONTROLLER + MYHISTORY_GROUP_REGISTER);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonGroup = new JSONObject(line);
	            	JSONObject mJsonGroup2 = mJsonGroup.getJSONObject("myHistoryGroup");
	            	
	            	// SUCCESS or FAIL
	            	mDayveGroup.setResult(mJsonGroup2.getString("result"));
	        	}
	        }
		} catch (Exception e) {
			// TODO: handle exception
			mDayveGroup.setResult("FAIL");
		}
		
		return mDayveGroup;
	}
	
	/**
	 * 사용자의 Group 목록을 가져 온다.
	 * 
	 * @param dayveGroup
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public ArrayList<DayveGroup> selectGroupList(DayveGroup dayveGroup) throws JSONException, IOException {
		Log.i(TAG, "selectGroupList");
		
		JSONObject jsonGroup = new JSONObject();
		
		jsonGroup.put("activateYn", dayveGroup.getActivateYn());
		jsonGroup.put("myHistoryMembersId", dayveGroup.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryGroup\":" + jsonGroup.toString() + "}";
		
		Log.i(TAG, "jsonGroup : " + jsonString);
		
		ArrayList<DayveGroup> groupList = new ArrayList<DayveGroup>();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_GROUP_CONTROLLER + MYHISTORY_GROUP_LIST);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "postUrl : " + postUrl);
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONArray jsonArray = new JSONArray(line);
	            	
	            	Log.i(TAG, "jsonArray.length() : " + jsonArray.length());
	            	
	            	for(int i=0 ; i<jsonArray.length() ; i++) {
	            		JSONObject mJsonGroup = jsonArray.getJSONObject(i);
	            		JSONObject mJsonGroup2 = mJsonGroup.getJSONObject("myHistoryGroup");
	            		
	            		DayveGroup mDayGroup = new DayveGroup();
	            		
	            		mDayGroup.setIdMyHistoryGroups(mJsonGroup2.getString("idMyHistoryGroups"));
	            		mDayGroup.setName(mJsonGroup2.getString("name"));
	            		mDayGroup.setComment(mJsonGroup2.getString("comment"));
	            		mDayGroup.setIconUrl(mJsonGroup2.getString("iconUrl"));
	            		mDayGroup.setOpenGroupYn(mJsonGroup2.getString("openGroupYn"));
	            		mDayGroup.setFavoriteYn(mJsonGroup2.getString("favoriteYn"));
	            		mDayGroup.setActivateYn(mJsonGroup2.getString("activateYn"));
	            		mDayGroup.setModifyDate(mJsonGroup2.getString("modifyDate"));
	            		mDayGroup.setRegisterDate(mJsonGroup2.getString("registerDate"));
	            		mDayGroup.setMyHistoryMembersId(mJsonGroup2.getString("myHistoryMembersId"));
	            		
//	            		Log.i(TAG, "idMyHistoryItems   : " + mDayGroup.getIdMyHistoryGroups());
//	            		Log.i(TAG, "name               : " + mDayGroup.getName());
//	            		Log.i(TAG, "comment            : " + mDayGroup.getComment());
//	            		Log.i(TAG, "iconUrl            : " + mDayGroup.getIconUrl());
//	            		Log.i(TAG, "openGroupYn        : " + mDayGroup.getOpenGroupYn());
//	            		Log.i(TAG, "favoriteYn         : " + mDayGroup.getFavoriteYn());
//	            		Log.i(TAG, "activateYn 		   : " + mDayGroup.getActivateYn());
//	            		Log.i(TAG, "modifyDate         : " + mDayGroup.getModifyDate());
//	            		Log.i(TAG, "registerDate       : " + mDayGroup.getRegisterDate());
//	            		Log.i(TAG, "myHistoryMembersId : " + mDayGroup.getMyHistoryMembersId());
//	            		Log.i(TAG, "-----------------------------------");
	            		
	            		groupList.add(mDayGroup);
	            	}
	        	}
	        }
	        
	        Log.i(TAG, "Success to select group list from server.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to select group list from server.");
		}
		
		return groupList;
	}
	
	/**
	 * Group 을 수정 한다.
	 * 
	 * @param dayveGroup
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveGroup updateGroup(DayveGroup dayveGroup) throws JSONException, IOException {
		Log.i(TAG, "updateGroup");
		
		JSONObject jsonGroup = new JSONObject();
		
		jsonGroup.put("idMyHistoryGroups", dayveGroup.getIdMyHistoryGroups());
		jsonGroup.put("name", dayveGroup.getName());
		jsonGroup.put("comment", dayveGroup.getComment());
		jsonGroup.put("iconUrl", dayveGroup.getIconUrl());
		jsonGroup.put("openGroupYn", dayveGroup.getOpenGroupYn());
		jsonGroup.put("favoriteYn", dayveGroup.getFavoriteYn());
		jsonGroup.put("activateYn", dayveGroup.getActivateYn());
		jsonGroup.put("modifyDate", dayveGroup.getModifyDate());
		jsonGroup.put("myHistoryMembersId", dayveGroup.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryGroup\":" + jsonGroup.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveGroup mDayveGroup = new DayveGroup();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_GROUP_CONTROLLER + MYHISTORY_GROUP_UPDATE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonCategory = new JSONObject(line);
	            	JSONObject mJsonCategory2 = mJsonCategory.getJSONObject("myHistoryGroup");
	            	
	            	// SUCCESS or FAIL
	            	mDayveGroup.setResult(mJsonCategory2.getString("result"));
	        	}
	        }
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return mDayveGroup;
	}
	
	/**
	 * Group 을 비활성화 한다.
	 * 
	 * @param dayveGroup
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveGroup updateDeactivateGroup(DayveGroup dayveGroup) throws JSONException, IOException {
		Log.i(TAG, "updateDeactivateGroup");
		
		JSONObject jsonGroup = new JSONObject();
		
		jsonGroup.put("idMyHistoryGroups", dayveGroup.getIdMyHistoryGroups());
//		jsonGroup.put("name", dayveGroup.getName());
//		jsonGroup.put("comment", dayveGroup.getComment());
//		jsonGroup.put("iconUrl", dayveGroup.getIconUrl());
//		jsonGroup.put("openGroupYn", dayveGroup.getOpenGroupYn());
//		jsonGroup.put("favoriteYn", dayveGroup.getFavoriteYn());
		jsonGroup.put("activateYn", dayveGroup.getActivateYn());
		jsonGroup.put("modifyDate", dayveGroup.getModifyDate());
		jsonGroup.put("myHistoryMembersId", dayveGroup.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryGroup\":" + jsonGroup.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveGroup mDayveGroup = new DayveGroup();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_GROUP_CONTROLLER + MYHISTORY_GROUP_DEACTIVATE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonCategory = new JSONObject(line);
	            	JSONObject mJsonCategory2 = mJsonCategory.getJSONObject("myHistoryGroup");
	            	
	            	// SUCCESS or FAIL
	            	mDayveGroup.setResult(mJsonCategory2.getString("result"));
	        	}
	        }
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return mDayveGroup;
	}
}
